package com.zdy.im.user.facade;

import com.sixeco.framework.common.data.BasePage;
import com.sixeco.framework.common.enums.SysResultCodeEnum;
import com.sixeco.framework.common.enums.TbStatusEnum;
import com.sixeco.framework.http.data.vo.ResponseResultList;
import com.sixeco.framework.http.exception.SystemRuntimeException;
import com.zdy.im.enums.ImResultCodeEnum;
import com.zdy.im.user.dto.request.ImRoomInfoRequestDto;
import com.zdy.im.user.dto.request.ImRoomUserShipRequestDto;
import com.zdy.im.user.dto.response.ImRoomInfoResponseDto;
import com.zdy.im.user.dto.response.ImRoomUserShipResponseDto;
import com.zdy.im.user.dto.response.UserInfoResponseDto;
import com.zdy.im.user.service.ImRoomInfoService;
import com.zdy.im.user.service.ImRoomUserShipService;
import com.zdy.im.user.service.UserInfoService;
import com.zdy.im.user.vo.request.*;
import com.zdy.im.user.vo.response.ImRoomInfoShowResponseVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.stream.Collectors;


/**
 * @Title: ImRoomInfoFacade.java
 * @Author 作者 : zdy
 * @CreateDate 创建时间: 2021-02-30
 * @version V1.0  
 *  <pre>
 * 修改记录
 *    修改后版本:     修改人：  修改日期:     修改内容:
 * </pre>
 * @Description: TODO(说明) 对象缓存统一模板实现类;  
 */
 
@Component
public class ImRoomInfoFacade {

	@Autowired
	private ImRoomInfoService imRoomInfoService;
	@Autowired
	private ImRoomUserShipService imRoomUserShipService;
	@Autowired
	private UserInfoService userInfoService;


	public ResponseResultList list(ImRoomInfoQueryRequestVo imRoomInfoQueryRequestVo){
		ImRoomInfoRequestDto imRoomInfoRequestDto = ImRoomInfoRequestDto.build( ).clone(imRoomInfoQueryRequestVo);

		BasePage page =  BasePage.build().toPageSize(imRoomInfoQueryRequestVo.getPageSize()).toPageNo(imRoomInfoQueryRequestVo.getPageNo());
		page.toParamObject(imRoomInfoRequestDto );

		//查询这个用户添加的群
		Set<Long> roomIds = new HashSet<>();
		List<ImRoomUserShipResponseDto> roomUsers = imRoomUserShipService.selectListByUserId(imRoomInfoQueryRequestVo.getMasterId());
		if(CollectionUtils.isEmpty(roomUsers)){
			return ResponseResultList.build();
		}
		roomUsers.forEach(e->{
			roomIds.add(e.getRoomId());
		});
		//查找群信息
		ResponseResultList<ImRoomInfoResponseDto> resultList = imRoomInfoService.getImRoomInfoByNextPage(page, roomIds);

		if(null == resultList || resultList.getList().isEmpty() ){
			return ResponseResultList.build();
		}
		List<ImRoomInfoShowResponseVo> listVo = new ArrayList<>();
		resultList.getList().forEach(e -> listVo.add(ImRoomInfoShowResponseVo.build().clone(e)));

		ResponseResultList list =  ResponseResultList.build().toList(listVo)
				.toIsNextPage(resultList.getIsNextPage())
				.toPageIndex(resultList.getPageIndex())
				.toTotal(resultList.getTotal());
		return list;
	}

	public ImRoomInfoResponseDto add(RoomInfoAddRequestVo roomInfoAddRequestVo){
		Set<Long> userIds = new HashSet<>();
		if(StringUtils.isNotBlank(roomInfoAddRequestVo.getUserIds())){
			List<String> ids =  Arrays.asList(roomInfoAddRequestVo.getUserIds().split(","));
			userIds.addAll(ids.stream().map(a->{return Long.valueOf(a);}).collect(Collectors.toSet()));
		}

		//创建群
		ImRoomInfoRequestDto imRoomInfoRequestDto = ImRoomInfoRequestDto.build()
				.toRoomImg(roomInfoAddRequestVo.getRoomImg())
				.toCreateId(roomInfoAddRequestVo.getMasterId())
				.toRoomName(roomInfoAddRequestVo.getRoomName())
				.toMasterId(roomInfoAddRequestVo.getMasterId())//群主id
				.toStatus(TbStatusEnum.ENABLE.index())
				.toForbidSpeech(0);//全群禁言(1-已禁言,0-未禁言)
		ImRoomInfoResponseDto imRoomInfoResponseDto = imRoomInfoService.saveImRoomInfo(imRoomInfoRequestDto);
		if(imRoomInfoResponseDto == null){
			throw new SystemRuntimeException(SysResultCodeEnum.SYS_UNKOWNN_FAIL);
		}
		userIds.add(roomInfoAddRequestVo.getMasterId());//添加群主
		Map<Long, UserInfoResponseDto> userMap = userInfoService.getUserInfoByIds( userIds);

		//添加群用户关系
		List<ImRoomUserShipRequestDto> roomUserList = new ArrayList<>();
		userIds.forEach(e->{
			ImRoomUserShipRequestDto imRoomUserShipRequestDto = ImRoomUserShipRequestDto.build()
					.toRoomId(imRoomInfoResponseDto.getId())//群id
					.toUserId(e)
					.toForbidSpeech(0)//全群禁言(1-已禁言,0-未禁言)
					.toRoomSet(TbStatusEnum.ENABLE.index())//群设置 0不接受消息 1接收消息
					.toStatus(TbStatusEnum.ENABLE.index());//删除状态(1-正常,0-已删除)
			imRoomUserShipRequestDto.toUserRole((e.equals(roomInfoAddRequestVo.getMasterId())) ? 99 : 0);//类型 0 用户，1.管理员，99.群主
			if(!CollectionUtils.isEmpty(userMap) && userMap.get(e) != null){
				imRoomUserShipRequestDto.toNickName(userMap.get(e).getUserName());//用户群昵称/备注昵称
			}
			roomUserList.add(imRoomUserShipRequestDto);
		});
		if(!CollectionUtils.isEmpty(roomUserList)){
			imRoomUserShipService.saveBatchImRoomUserShip(roomUserList,roomUserList.size());
		}
		return imRoomInfoResponseDto;
	}

	/**
	 * 修改群头像
	 * @param userVo
	 * @return
	 */
	public boolean upRoomImg( RoomImgRequestVo userVo){
		ImRoomInfoResponseDto imRoomInfoResponseDto = imRoomInfoService.getImRoomInfoById(userVo.getRoomId());
		if(imRoomInfoResponseDto == null){
			throw new SystemRuntimeException(ImResultCodeEnum.IM_USER_NOT_EXIST);
		}
		imRoomInfoResponseDto.setRoomImg(userVo.getRoomImg());//修改群头像
		return imRoomInfoService.updateImRoomInfo(ImRoomInfoRequestDto.build().clone(imRoomInfoResponseDto));
	}

	/**
	 * 修改群公告/简介/群名称/禁言
	 * @param userVo
	 * @return
	 */
	public boolean upRoomInfo( RoomInfoRequestVo userVo){
		ImRoomInfoResponseDto imRoomInfoResponseDto = imRoomInfoService.getImRoomInfoById(userVo.getRoomId());
		if(imRoomInfoResponseDto == null){
			throw new SystemRuntimeException(ImResultCodeEnum.IM_USER_NOT_EXIST);
		}
		if(StringUtils.isNotBlank(userVo.getRoomNotice())){
			imRoomInfoResponseDto.setRoomNotice(userVo.getRoomNotice());//修改群公告
		}
		if(StringUtils.isNotBlank(userVo.getRemarks())){
			imRoomInfoResponseDto.setRemarks(userVo.getRemarks());//修改群简介
		}
		if(StringUtils.isNotBlank(userVo.getRoomName())){
			imRoomInfoResponseDto.setRoomName(userVo.getRoomName());//修改群名称
		}
		if(userVo.getForbidSpeech() > 0){
			imRoomInfoResponseDto.setForbidSpeech(userVo.getForbidSpeech());//全群禁言(1：已禁言,-1：未禁言)
		}else if(userVo.getForbidSpeech() == -1){
			imRoomInfoResponseDto.setForbidSpeech(0);//全群禁言(1-已禁言,0-未禁言)
		}
		return imRoomInfoService.updateImRoomInfo(ImRoomInfoRequestDto.build().clone(imRoomInfoResponseDto));
	}


	/**
	 * 修改群公告/简介/群名称
	 * @param userVo
	 * @return
	 */
	public boolean delRoom( RoomRequestVo userVo){
		ImRoomInfoResponseDto imRoomInfoResponseDto = imRoomInfoService.getImRoomInfoById(userVo.getRoomId());
		if(imRoomInfoResponseDto == null){
			throw new SystemRuntimeException(ImResultCodeEnum.IM_USER_NOT_EXIST);
		}

		//解散群好友关系
		List<ImRoomUserShipResponseDto> roomList = imRoomUserShipService.selectListByRoomId(userVo.getRoomId());
		if(!CollectionUtils.isEmpty(roomList)){
			List<ImRoomUserShipRequestDto> rooms = new ArrayList<>();
			roomList.forEach(e->{
				ImRoomUserShipRequestDto vo = ImRoomUserShipRequestDto.build().clone(e);
				vo.setStatus(TbStatusEnum.DISABLE.index());//删除状态(1-正常,0-已删除)
				rooms.add(vo);
			});
			imRoomUserShipService.saveBatchImRoomUserShip(rooms ,rooms.size());
		}

		imRoomInfoResponseDto.setStatus(TbStatusEnum.DISABLE.index());//删除状态(1-正常,0-已删除)
		return imRoomInfoService.updateImRoomInfo(ImRoomInfoRequestDto.build().clone(imRoomInfoResponseDto));
	}
}
